// pages/signSucceed/signSucceed.js
import api from "../../config/api"
import request from "../../utils/request"
import { shareOptions } from "../../utils/access"
import { getBarAndTitleHeight, getXsScreen, jump, stringify, getStorage, goBack, removeStorage } from "../../utils/utils"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户信息
    userInfo: {},
    // 拍照结果信息
    taskData: {},
    // 累计分类天数
    classDays: 0,
    // 分类签到天数
    signDays: 0,
    // 红包是否已打开
    envelopeOpened: false,
    // 红包金额
    envelopeAmount: 0,
    // 是否隐藏红包入口
    entranceHide: false,
    // 拆样式
    dismantleClass: '',
    // 金币样式
    goldClass: '',
    // 开红包接口失败 
    requestFail: false,
    // 信号栏高度
    ...getBarAndTitleHeight(),
    // 是否是小屏幕尺寸
    ...getXsScreen(),
    // 是否从PK活动进入
    fromActivity: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserData()
    this.setData({
      taskData: options,
      signDays: (+options?.signDays || 0) + 1,
      entranceHide: !options?.signInRedPacket,
      fromActivity: Number(getStorage('fromActivity')) ===1
    })
  },
  	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
    this.modal = this.selectComponent('#modal')
    if(!this.data.entranceHide){
      this.openModal()
    }
	},
  // 获取用户信息
  async getUserData(){
    const userInfo = getStorage('userInfo')

    // 设置短昵称
    const nameArray = Array.from(userInfo?.nickName || '')
    const shortName = nameArray.slice(0, 4).join('')
    userInfo.shortName = nameArray.length > 4 ? `${shortName}...` : shortName

    const res = await request.get(api.userDays)

    this.setData({
      userInfo,
      classDays: res?.data?.accumulatedClassifyDays,
      signDays: res?.data?.signInDays,
    })
  },
  // 打开红包弹窗
  openModal() {
    this.setData({
      requestFail: false,
      entranceHide: true,
      dismantleClass: 'scale',
    })
    this.modal.show()
  },
  // 关闭红包弹窗
  closeModal() {
    if (this.data.envelopeOpened) {
      this.modal.hide()
    }
  },
  // 打开红包
  openEnvelope() {
    if (this.loading) return
    this.loading = true
    // 隐藏拆
    this.setData({
      dismantleClass: 'hide',
    }, () => {
      setTimeout(async () => {
        // 显示金币并旋转
        this.setData({
          goldClass: 'spin',
          dismantleClass: '',
        })
        // 接口开始时间
        const startTime = Date.now()
        // 调接口开红包
        const res = await request.get(
          api.collarEnvelope,
          { signInId: this.data.taskData.signInId },
          { loading: false }
        )
        console.log('开红包接口返回：', res)
        // 接口响应时间
        const requestTime = Date.now() - startTime
        // 不足2000毫秒延迟
        if (requestTime < 2000) {
          await new Promise((resolve) => {
            setTimeout(() => {
              resolve()
            }, 2000 - requestTime)
          })
        }
        if (res?.httpStatus === 200) {
          // 隐藏金币
          this.setData({
            goldClass: 'hide'
          }, () => {
            // 显示金额
            setTimeout(() => {
              this.setData({
                goldClass: '',
                envelopeAmount: res?.data || 0,
                envelopeOpened: true,
              })
              this.loading = false
            }, 540)
          })
        } else {
          // 隐藏金币显示拆
          this.setData({
            dismantleClass: 'scale',
            goldClass: '',
            requestFail: true,
          })
          this.loading = false
        }
      }, 540)
    })
  },
  // 跳转桶内详情
  goBucketAnalyse(){
    const { taskData } = this.data
    const { ingredient, bucketType, url } = taskData || {}

    jump('bucketAnalyse', {
      url,
      ingredient,
      bucketType,
      taskData: stringify(taskData || {})
    })
  },
  // 跳转到首页
  goHome(){
    jump('index')
  },
  // 返回上一页
  back(){
    goBack()
  },
  // 返回活动
  handleActivity(){
    goBack(3)
    removeStorage('fromActivity')
  },
  // 用户点击右上角分享
  onShareAppMessage(event) {
    const { taskData } = this.data
    if (event.from === 'button' && taskData?.ifTarget) {
      return shareOptions('inviteWechatFriend', event)
    }
    return shareOptions('award', event)
  },
})